/*
 * @Author: Kiro AI Assistant
 * @Date: 2025-01-10
 * @Description: 进度条滑块组件 - 性能优化版本
 */

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../viewmodels/music_player_view_model.dart';

/// 进度条滑块组件
/// 使用 ValueListenableBuilder 实现细粒度更新，避免整个页面重建
class ProgressSliderWidget extends StatefulWidget {
  /// 滑块颜色
  final Color? activeColor;

  /// 非活动滑块颜色
  final Color? inactiveColor;

  /// 滑块拇指颜色
  final Color? thumbColor;

  /// 滑块高度
  final double trackHeight;

  /// 拇指半径
  final double thumbRadius;

  /// 是否显示时间标签
  final bool showTimeLabels;

  /// 时间标签样式
  final TextStyle? timeLabelStyle;

  /// 是否启用交互
  final bool enabled;

  /// 自定义进度值（用于静态显示）
  final double? customProgress;

  /// 自定义时长（用于静态显示）
  final Duration? customDuration;

  /// 自定义位置（用于静态显示）
  final Duration? customPosition;

  /// 进度变化回调
  final ValueChanged<Duration>? onSeek;

  const ProgressSliderWidget({
    super.key,
    this.activeColor,
    this.inactiveColor,
    this.thumbColor,
    this.trackHeight = 2.0,
    this.thumbRadius = 6.0,
    this.showTimeLabels = true,
    this.timeLabelStyle,
    this.enabled = true,
    this.customProgress,
    this.customDuration,
    this.customPosition,
    this.onSeek,
  });

  @override
  State<ProgressSliderWidget> createState() => _ProgressSliderWidgetState();
}

class _ProgressSliderWidgetState extends State<ProgressSliderWidget> {
  bool _isDragging = false;
  double _dragValue = 0.0;

  @override
  Widget build(BuildContext context) {
    return Consumer<MusicPlayerViewModel>(
      builder: (context, viewModel, child) {
        return Column(
          children: [
            // 进度条
            _buildProgressSlider(viewModel),

            // 时间标签
            if (widget.showTimeLabels) ...[
              const SizedBox(height: 8),
              _buildTimeLabels(viewModel),
            ],
          ],
        );
      },
    );
  }

  /// 构建进度条滑块
  Widget _buildProgressSlider(MusicPlayerViewModel viewModel) {
    // 如果有自定义进度值，使用静态显示
    if (widget.customProgress != null) {
      return _buildStaticSlider();
    }

    // 使用 ValueListenableBuilder 监听位置和时长变化
    return ValueListenableBuilder<Duration>(
      valueListenable: viewModel.position,
      builder: (context, position, child) {
        return ValueListenableBuilder<Duration>(
          valueListenable: viewModel.duration,
          builder: (context, duration, child) {
            final progress = duration.inMilliseconds > 0
                ? position.inMilliseconds / duration.inMilliseconds
                : 0.0;

            return SliderTheme(
              data: _buildSliderTheme(context),
              child: Slider(
                value: _isDragging ? _dragValue : progress.clamp(0.0, 1.0),
                onChanged: widget.enabled ? _onSliderChanged : null,
                onChangeStart: widget.enabled ? _onSliderChangeStart : null,
                onChangeEnd: (value) => _onSliderChangeEnd(value, viewModel),
              ),
            );
          },
        );
      },
    );
  }

  /// 构建静态滑块（用于非当前播放的音乐）
  Widget _buildStaticSlider() {
    return SliderTheme(
      data: _buildSliderTheme(context),
      child: Slider(
        value: widget.customProgress?.clamp(0.0, 1.0) ?? 0.0,
        onChanged: widget.enabled && widget.onSeek != null
            ? (value) {
                final duration = widget.customDuration ?? Duration.zero;
                final seekPosition = Duration(
                  milliseconds: (duration.inMilliseconds * value).round(),
                );
                widget.onSeek!(seekPosition);
              }
            : null,
      ),
    );
  }

  /// 构建时间标签
  Widget _buildTimeLabels(MusicPlayerViewModel viewModel) {
    // 如果有自定义时间，使用静态显示
    if (widget.customPosition != null && widget.customDuration != null) {
      return _buildStaticTimeLabels();
    }

    return ValueListenableBuilder<Duration>(
      valueListenable: viewModel.position,
      builder: (context, position, child) {
        return ValueListenableBuilder<Duration>(
          valueListenable: viewModel.duration,
          builder: (context, duration, child) {
            return Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  _formatDuration(_isDragging
                      ? Duration(
                          milliseconds:
                              (duration.inMilliseconds * _dragValue).round())
                      : position),
                  style:
                      widget.timeLabelStyle ?? _defaultTimeLabelStyle(context),
                ),
                Text(
                  _formatDuration(duration),
                  style:
                      widget.timeLabelStyle ?? _defaultTimeLabelStyle(context),
                ),
              ],
            );
          },
        );
      },
    );
  }

  /// 构建静态时间标签
  Widget _buildStaticTimeLabels() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          _formatDuration(widget.customPosition ?? Duration.zero),
          style: widget.timeLabelStyle ?? _defaultTimeLabelStyle(context),
        ),
        Text(
          _formatDuration(widget.customDuration ?? Duration.zero),
          style: widget.timeLabelStyle ?? _defaultTimeLabelStyle(context),
        ),
      ],
    );
  }

  /// 构建滑块主题
  SliderThemeData _buildSliderTheme(BuildContext context) {
    return SliderTheme.of(context).copyWith(
      trackHeight: widget.trackHeight,
      thumbShape: RoundSliderThumbShape(
        enabledThumbRadius: widget.thumbRadius,
      ),
      overlayShape: RoundSliderOverlayShape(
        overlayRadius: widget.thumbRadius * 2,
      ),
      activeTrackColor: widget.activeColor ?? Theme.of(context).primaryColor,
      inactiveTrackColor: widget.inactiveColor ?? Colors.grey.shade300,
      thumbColor: widget.thumbColor ?? Theme.of(context).primaryColor,
      overlayColor: (widget.thumbColor ?? Theme.of(context).primaryColor)
          .withOpacity(0.2),
    );
  }

  /// 默认时间标签样式
  TextStyle _defaultTimeLabelStyle(BuildContext context) {
    return TextStyle(
      fontSize: 12,
      color: Colors.grey.shade600,
    );
  }

  /// 滑块值变化处理
  void _onSliderChanged(double value) {
    setState(() {
      _dragValue = value;
    });
  }

  /// 滑块开始拖拽处理
  void _onSliderChangeStart(double value) {
    setState(() {
      _isDragging = true;
      _dragValue = value;
    });
  }

  /// 滑块结束拖拽处理
  void _onSliderChangeEnd(double value, MusicPlayerViewModel viewModel) {
    setState(() {
      _isDragging = false;
    });

    // 执行跳转
    final duration = viewModel.duration.value;
    final seekPosition = Duration(
      milliseconds: (duration.inMilliseconds * value).round(),
    );

    if (widget.onSeek != null) {
      widget.onSeek!(seekPosition);
    } else {
      viewModel.seekTo(seekPosition);
    }
  }

  /// 格式化时长显示
  String _formatDuration(Duration duration) {
    final minutes = duration.inMinutes;
    final seconds = duration.inSeconds % 60;
    return '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  }
}

/// 紧凑版进度条组件
/// 适用于悬浮播放器等空间有限的场景
class CompactProgressSliderWidget extends StatelessWidget {
  /// 滑块颜色
  final Color? activeColor;

  /// 非活动滑块颜色
  final Color? inactiveColor;

  /// 滑块高度
  final double trackHeight;

  const CompactProgressSliderWidget({
    super.key,
    this.activeColor,
    this.inactiveColor,
    this.trackHeight = 1.5,
  });

  @override
  Widget build(BuildContext context) {
    return Consumer<MusicPlayerViewModel>(
      builder: (context, viewModel, child) {
        return ValueListenableBuilder<Duration>(
          valueListenable: viewModel.position,
          builder: (context, position, child) {
            return ValueListenableBuilder<Duration>(
              valueListenable: viewModel.duration,
              builder: (context, duration, child) {
                final progress = duration.inMilliseconds > 0
                    ? position.inMilliseconds / duration.inMilliseconds
                    : 0.0;

                return LinearProgressIndicator(
                  value: progress.clamp(0.0, 1.0),
                  backgroundColor: inactiveColor ?? Colors.grey.shade300,
                  valueColor: AlwaysStoppedAnimation<Color>(
                    activeColor ?? Theme.of(context).primaryColor,
                  ),
                  minHeight: trackHeight,
                );
              },
            );
          },
        );
      },
    );
  }
}
